<script setup>
import MwTable from "./component/MwTableAlgorithm";
import SearchTable from "./component/SearchAlgorithm"
import MwDialog from "@/components/Dialog"
import { ElMessage, ElMessageBox } from 'element-plus'

import { CirclePlus, VideoPlay } from '@element-plus/icons-vue'
import { ref, reactive, getCurrentInstance, onMounted, watch } from "vue"
import moment from "moment";
import {isJSON} from '@/utils';
import { globalStore } from "@/store/global"
const globalVue = globalStore();

const instance = getCurrentInstance()
const _this = instance.appContext.config.globalProperties //vue3获取当前this

// 生命周期
onMounted(async () => {
  getTableData();
  algorithmSelect.value = await globalVue.getSelect('algorithmSelect');
  locationSelect.value = await globalVue.getSelect('locationSelect');
})

// --------------------- 下拉数据 --------------------
const algorithmSelect = ref([]);
const locationSelect = ref([]);

// --------------------- 表格数据 --------------------
const tableData = ref([]);
const tableLoading = ref(false);
const pagination = reactive({
  page: 1,
  size: 10,
  total: 0
});
const searchForm = reactive({});
function getTableData() {
  // 查询司机
  let params = {
    ...pagination,
    ...searchForm
  }
  tableLoading.value = true;
  instance.proxy.$http.get('statistics.getAlgorithmList',{ params }).then(res=>{
    let {content, totalElements} = res.data;
    tableData.value = content;
    pagination.total = totalElements;
    tableLoading.value = false;
  }).catch(err => tableLoading.value = false)
}
function onRefresh(){
  Object.keys(searchForm).map(key => {
    delete searchForm[key];
  })
  getTableData();
}
function onEdit(row){
  dialogData.rowData = row;
  changeDialog(true, 'Edit');
};
function onDelete(row){
  ElMessageBox.confirm(
    'Confirm Delete ？',
    'Delete',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel'
    }
  )
    .then(() => {
      instance.proxy.$http.delete('statistics.deleteAlgorithm', {data: {id: row.id + ''}}).then(res=>{
        getTableData();
        ElMessage({
          type: 'success',
          message: 'Delete successfully',
        })
      })
    })
    .catch(() => {})
}


// ----------------- 弹框数据 --------------------
let dialogData = reactive({
  show: false,
  algorithmTitle: ['People Track Identification', 'People Face Expression Identification', 'People Risk Scoring', 'Falling Detection', 'Remnant Detection'],
  state: 'Edit', // Add  Edit
  form: {},
  rowData: null,
})
function dialogSubmit(){
  if (dialogData.state == 'Edit') {
    console.log(dialogData.form, '= edit');
    console.log(formatDetectionArea(dialogData.form));
    // instance.proxy.$http.post('statistics.insertAlgorithm', dialogData.form).then(res=>{
    //   getTableData();
    //   changeDialog(false);
    // })
  }
}
function changeDialog(show, state) {
  dialogData.show = show;
  if (show) {
    let form = {
      detectionArea: {}
    };
    if (dialogData.rowData.detectionArea) {
      if(isJSON(dialogData.rowData.detectionArea)){
        let detectionArea = JSON.parse(dialogData.rowData.detectionArea);
        detectionArea.polygons[0].data.forEach((j, ind) => (form.detectionArea['q' + (ind + 1)] = j));
      }else{
        form['detectionArea'] = dialogData.rowData.detectionArea;
      }
    }
    if(dialogData.rowData.detectionPeriod){
      form.detectionPeriod = dialogData.rowData.detectionPeriod.split('-').map(x => moment('2023-01-01 ' + x + ':00'));
    }
    if (dialogData.rowData.parameter) {
      dialogData.rowData.parameter.split(',').forEach(y => {
        let keyValue = y.split(':');
        form[keyValue[0]] = keyValue[1];
      })
    }
    form['isAble'] = !!dialogData.rowData.isAble;
    dialogData.form = {};
    Object.assign(dialogData.form, dialogData.rowData, form);
  } else {

  }
  if(state) dialogData.state = state;
}

function formatDetectionArea(data, type = ''){
  let obj = {"polygons": [{"data": []}]}, params = {};
  Object.keys(data['detectionArea']).forEach(i => {
    obj.polygons[0].data.push(data['detectionArea'][i])
  })
  params['detectionArea'] = JSON.stringify(obj);
  let timeSlot = data.detectionPeriod.concat();
  params['detectionPeriod'] = timeSlot.map(i => moment(i).format('HH:mm')).join("-");
  if(data.type == 1){
    params['parameter'] = [`detection_min_size:${data?.detection_min_size}`, `detection_max_size:${data?.detection_max_size}`] + '';
  }
  if(data.type == 3){
    params['parameter'] = [
      `wearing glasses:${data?.wearingGlasses}`, 
      `hat:${data?.hat}`,
      `age:${data?.age}`,
      `gender:${data?.gender}`,
      `backpack:${data?.backpack}`,
      `handbag:${data?.handbag}`,
    ] + '';
  }
  if(data.type == 5){
    params['parameter'] = [`alert_time_threshold:${data?.alert_time_threshold}`, `alert_detection_interval:${data?.alert_detection_interval}`] + '';
  }
  params.isAble = Number(data.isAble);
  params.type = data.type;
  params.algorithmId = data.algorithmId;
  return params;
}
</script>
<template>
  <div class="table_index">
    <SearchTable 
      :locationSelect="locationSelect" 
      :algorithmSelect="algorithmSelect" 
      :searchForm="searchForm" 
      @search="getTableData"
      @refresh="onRefresh" />
    <div class="table_content">
      <mw-table
        :loading="tableLoading"
        :data="tableData"
        :pagination="pagination"
        @paginationChange="getTableData"
        @operate1="onEdit"
        @operate2="onDelete"
      ></mw-table>
    </div>
  </div>

  
  <mw-dialog
    :show="dialogData.show"
    title="Configuration Algorithm"
    width="600px"
    @submit="dialogSubmit"
    @close="changeDialog(false)"
  >
    <div class="dialog_title">{{dialogData.algorithmTitle[dialogData.rowData.type - 1]}}</div>

    <el-form class="dialog_form collapse_form" :model="dialogData.form" label-width="210px" v-if="dialogData.rowData.type == 1">
      <el-form-item label="Detection_Min_Size">
        <el-input v-model="dialogData.form.detection_min_size" type="number" class="value_input" placeholder="Enter" clearable >
          <template #append>MB</template>
        </el-input>
      </el-form-item>
      <el-form-item label="Detection_Max_Size">
        <el-input v-model="dialogData.form.detection_max_size" type="number" class="value_input" placeholder="Enter" clearable >
          <template #append>MB</template>
        </el-input>
      </el-form-item>
      <el-form-item label="Detection Period">
        <el-time-picker
          v-model="dialogData.form.detectionPeriod"
          is-range
          format="HH:mm"
          clearable
          range-separator="To"
          start-placeholder="Start time"
          end-placeholder="End time"
        />
      </el-form-item>
      <el-form-item label="Detection Area">
        <div class="four_box">
          <el-input v-model="dialogData.form.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
        </div> 
      </el-form-item>
    </el-form>
    <el-form class="dialog_form collapse_form" :model="dialogData.form" label-width="210px" v-if="dialogData.rowData.type == 2">
      <el-form-item label="Detection Period">
        <el-time-picker
          v-model="dialogData.form.detectionPeriod"
          is-range
          format="HH:mm"
          clearable
          range-separator="To"
          start-placeholder="Start time"
          end-placeholder="End time"
        />
      </el-form-item>
      <el-form-item label="Detection Area">
        <div class="four_box">
          <el-input v-model="dialogData.form.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
        </div> 
      </el-form-item>
    </el-form>
    <el-form class="dialog_form collapse_form" :model="dialogData.form" label-width="210px" v-if="dialogData.rowData.type == 3">
      <el-form-item label="Gender">
        <el-select class="value_input" v-model="dialogData.form.gender" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.genderSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Age">
        <el-select class="value_input" v-model="dialogData.form.age" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.ageSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Hat">
        <el-select class="value_input" v-model="dialogData.form.hat" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.hatSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Wearing Glasses">
        <el-select class="value_input" v-model="dialogData.form.wearingGlasses" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.wearingGlassesSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Backpack">
        <el-select class="value_input" v-model="dialogData.form.backpack" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.backpackSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Handbag">
        <el-select class="value_input" v-model="dialogData.form.handbag" placeholder="Please select" filterable clearable>
          <el-option v-for="item in globalVue.handbagSelect" :key="item.id" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="Detection Period">
        <el-time-picker
          v-model="dialogData.form.detectionPeriod"
          is-range
          format="HH:mm"
          clearable
          range-separator="To"
          start-placeholder="Start time"
          end-placeholder="End time"
        />
      </el-form-item>
      <el-form-item label="Detection Area">
        <div class="four_box">
          <el-input v-model="dialogData.form.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
        </div> 
      </el-form-item>
    </el-form>
    <el-form class="dialog_form collapse_form" :model="dialogData.form" label-width="210px" v-if="dialogData.rowData.type == 4">
      <el-form-item label="Detection Period">
        <el-time-picker
          v-model="dialogData.form.detectionPeriod"
          is-range
          format="HH:mm"
          clearable
          range-separator="To"
          start-placeholder="Start time"
          end-placeholder="End time"
        />
      </el-form-item>
      <el-form-item label="Detection Area">
        <div class="four_box">
          <el-input v-model="dialogData.form.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
        </div> 
      </el-form-item>
    </el-form>
    <el-form class="dialog_form collapse_form" :model="dialogData.form" label-width="210px" v-if="dialogData.rowData.type == 5">
      <el-form-item label="Alert_Time_Threshold">
        <el-input v-model="dialogData.form.alert_time_threshold" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Alert_Detection_Interval">
        <el-input v-model="dialogData.form.alert_detection_interval" class="value_input" placeholder="Enter" clearable />
      </el-form-item>
      <el-form-item label="Detection Period">
        <el-time-picker
          v-model="dialogData.form.detectionPeriod"
          is-range
          format="HH:mm"
          clearable
          range-separator="To"
          start-placeholder="Start time"
          end-placeholder="End time"
        />
      </el-form-item>
      <el-form-item label="Detection Area">
        <div class="four_box">
          <el-input v-model="dialogData.form.detectionArea.q1" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q2" class="value_input" style="width: 48%" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q3" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
          <el-input v-model="dialogData.form.detectionArea.q4" class="value_input" style="width: 48%;margin-top: 10px" placeholder="Enter" clearable />
        </div> 
      </el-form-item>
    </el-form>
  </mw-dialog>
</template>
<style lang="less" scoped>
.dialog_title{
  color: #ffffff;
  margin-bottom: 20px;
}
</style>